//
//  JwHttpHandel.m
//  JwPack
//
//  Created by 陈警卫 on 2024-08-29.
//

#import "JwHttpHandel.h"
#import "JwHttpManager.h"
//#import "JwExService.h"

@implementation JwHttpHandel

+ (BOOL)handelShouldSuccessWithConfig:(JwHttpConfig *)config {
    if (config.state == JwHttpStateResponse) {
        NSInteger code = [config.response[@"code"] integerValue];
        if (code == JwHttpCodeFinish) {
            config.state = JwHttpStateFinish;
            [self handelResponseWithConfig:config];
            [self handelViewWithConfig:config];
            return YES;
        } else {
            [self handelErrorResponseWithConfig:config];
        }
    }
    return NO;
}

+ (void)handelResponseWithConfig:(JwHttpConfig *)config {
    if (config.decodeModelName.length > 0) {
        id model = nil;
        id value = config.response;
        
        id currentValue = (NSMutableDictionary *)[value mutableCopy];
        NSArray *paths = [config.decodePath componentsSeparatedByString:@"."];
        
        for (int i = 0; i < paths.count; i++) {
            NSString *path = paths[i];
            if (currentValue == nil) {
                break;
            }
            id nextValue = currentValue[path];
            if (i + 1 < paths.count) {
                if ([nextValue isKindOfClass:[NSDictionary class]] || [nextValue isKindOfClass:[NSArray class]]) {
                    currentValue = (NSMutableDictionary *)[nextValue mutableCopy];
                } else {
                    currentValue = nil;
                    break;
                }
            } else {
                currentValue = nextValue;
                break;
            }
        }
        
        if (currentValue) {
            Class modelClass = NSClassFromString(config.decodeModelName);
            
            if ([currentValue isKindOfClass:[NSArray class]]) {
                model = [modelClass arrayOfModelsFromDictionaries:currentValue];
            } else if ([currentValue isKindOfClass:[NSDictionary class]]) {
                model = [[modelClass alloc] initWithDictionary:currentValue error:nil];
            }
            config.decode = model;
        }
    }
}

+ (void)handelErrorResponseWithConfig:(JwHttpConfig *)config {
    NSInteger code = [config.response[@"code"] integerValue];
    if (code == JwHttpCodeRefreshToken) {
        if ([JwHttpManager shared].lock) {
            // 刷新原接口
            // [[[JwExService alloc] init] refresh_config:config comple:config.comple];
        } else {
            // 刷新token
            [JwHttpManager shared].lock = YES;
            /**
             刷新完成后
             1 -> [JwHttpManager shared].lock = NO;
             2 -> [[JwHttpManager shared].condition broadcast];
             3 -> 刷新原接口
             */
            /**
             kJwBlock(config);
             [[[JwExService alloc] init] refreshToken_comple:^(JwHttpConfig * _Nonnull config) {
             [[[JwExService alloc] init] refresh_config:bconfig comple:bconfig.comple];
             [JwHttpManager shared].lock = NO;
             [[JwHttpManager shared].condition broadcast];
             }];             
             */
        }
    } else if (code == JwHttpCodeLoginAgain) {
        [self handelViewWithConfig:config];
    } else {
        [self handelErrorHttpWithConfig:config];
    }
}

+ (void)handelErrorHttpWithConfig:(JwHttpConfig *)config {
    
    [self handelViewWithConfig:config];
    
    if ([config.owners[kJwHttpOwnerErrorHudKey] isEqualToString:@"0"]) {
        return;
    } else {
        if (config.state == JwHttpStateError) {
            [JwProgressHUD showError:kJwLocalizedString(@"Network error")];
        } else {
            if (config.state == JwHttpStateResponse) {
                NSError *error = [NSError errorWithDomain:(config.response[@"message"] ?: @"Unknown data error")
                                                     code:[config.response[@"code"] integerValue] userInfo:nil];
                config.error = error;
                [JwProgressHUD showError:error.domain];
            }
        }
    }
}

+ (void)handelViewWithConfig:(JwHttpConfig *)config {
    if (config.state == JwHttpStateStart) {
        
    } else if (config.state == JwHttpStateRequest) {
        if (config.loadView && !config.hud) {
            JwProgressHUD *hud = [JwProgressHUD showHUDTo:config.loadView];
            config.hud = hud;
        }
    } else if (config.state == JwHttpStateResponse || config.state == JwHttpStateError) {
        if (config.hud) {
            [config.hud hideAnimated:YES];
        }
        if (config.scrollView) {
            [config.scrollView jw_mj_headerEndRefreshing];
            [config.scrollView jw_mj_footerEndRefreshing];
        }
    }
}


@end
